/*
 * @(#)CheckAndCreateLocalTable.java   1.0  2021年11月16日
 * 
 * Copyright (c)	2014-2020. All Rights Reserved.	GuangZhou hhmk Technology Company LTD.
 */
package com.swift.dts.init;

import java.io.IOException;
import java.io.InputStream;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.swift.dts.db.LocalDbDataSource;
import com.swift.util.type.ByteUtil;
import com.swift.util.type.TypeUtil;

/**
 * 添加说明
 * 
 * @author zhengjiajin
 * @version 1.0 2021年11月16日
 */
@Component
public class CheckAndCreateLocalTable {

    @Autowired
    private LocalDbDataSource localDbDataSource;

    @PostConstruct
    public void init() {
        for (LocalTable localTable : LocalTable.values()) {
            if (isExis(localTable.getTableName())) continue;
            InputStream inputStream = this.getClass().getResourceAsStream(localTable.getSqlPathFile());
            String createTableSql = new String(ByteUtil.getInputStream(inputStream));
            localDbDataSource.execute(createTableSql);
            try {
                inputStream.close();
            } catch (IOException e) {
            }
        }
    }

    /**
     * 
     */
    private boolean isExis(String checkName) {
        try {
            DatabaseMetaData meta = localDbDataSource.getConnection().getMetaData();
            ResultSet res = meta.getTables(null, null, null, new String[] { "TABLE" });
            while (res.next()) {
                String tableName = res.getString("TABLE_NAME");
                if (TypeUtil.isNull(tableName)) continue;
                if (tableName.equalsIgnoreCase(checkName)) return true;
            }
            return false;
        } catch (Exception ex) {
            return false;
        }
    }
}
